package org.example.stack;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author liyishan
 * @date 2024/10/9 16:25
 * @apiNote
 */

public class StackByQueue<T> {
    private Queue<T> queue;
    private Queue<T> tempQueue;
    public StackByQueue() {
        queue = new LinkedList<>();
        tempQueue = new LinkedList<>();
    }
    public boolean isEmpty(){
        return queue.isEmpty();
    }
    public void push(T element){
        queue.offer(element);
    }
    public T pop(){
        if(isEmpty()){
            throw new RuntimeException("StackByQueue is empty");
        }
        while(queue.size() > 1){
            tempQueue.offer(queue.poll());
        }
        T element = queue.poll();
        Queue<T> temp = queue;
        queue = tempQueue;
        tempQueue = temp;
        return element;
    }

    public T peek(){
        if(isEmpty()){
            throw new RuntimeException("StackByQueue is empty");
        }
        while(queue.size() > 1){
            tempQueue.offer(queue.poll());
        }
        T element = queue.peek();
        queue.offer(tempQueue.poll());
        Queue<T> temp = queue;
        queue = tempQueue;
        tempQueue = temp;
        return element;
    }
}
